<template>
  <div class="read-wrap">
    <!-- 概况 -->
    <div class="overview text-center mb-10px">
      <div class="text-333 font-normal">
        <span>总得分：</span>
        <span
          class="font-semibold"
          :class="`text-${getScoreClass(stats.studentScore / stats.questionScore)}`"
          style="font-size: 0.5rem; line-height: 0.7rem"
          >{{ stats.studentScore }}</span
        >
        <span :class="`text-${getScoreClass(stats.studentScore / stats.questionScore)}`">分</span>
        <span>/{{ stats.questionScore }}分</span>
      </div>
    </div>
    <div class="score text-333 flex justify-between items-center px-64px box-border">
      <span>准确度：{{ stats.pronunciation }} 分</span>
      <span>流畅度：{{ stats.fluency }}分</span>
      <span>完整度：{{ stats.integrity }}分</span>
    </div>
    <div class="play flex justify-between">
      <div class="play-btn item flex-center box-border">
        <img
          style="margin-right: 0.06rem"
          src="static/icons/speaker.png"
          alt=""
          srcset=""
          :data-question-id="stats.questionId"
          :data-audio-src="stats.stemAudio"
        />
        <span>原音</span>
      </div>
      <div class="play-btn item flex-center box-border">
        <img
          style="margin-right: 0.06rem"
          src="static/icons/my-records.png"
          alt=""
          srcset=""
          :data-question-id="stats.questionId"
          :data-audio-src="stats.selfAudio"
        />
        <span>录音</span>
      </div>
    </div>
    <div style="font-size: 0.2rem" v-html="stats.stem.html"></div>
    <div class="hr my-30px"></div>
    <div class="" style="font-size: 18px; color: #333333">
      <div>准确度：朗读发音的准确程度，如单词发音、重音、重读等。 </div>
      <div>流畅度：朗读的流畅程度，如停顿、语调、节奏等。</div>
      <div>完整度：朗读内容的完整程度，如是否漏读、乱读。</div>
      <div class="mt-20px">根据发音得分文本会展示不同颜色</div>
      <div class="rules mt-6px flex">
        <div class="text-30C9A1 text-center mr-10px">
          <div>Nothing is</div>
          <span class="arrow bg-30C9A1 my-10px inline-block"></span>
          <div>发音很棒</div>
        </div>
        <div class="text-F8AC23 text-center mr-10px">
          <div>impossible</div>
          <span class="arrow bg-F8AC23 my-10px inline-block"></span>
          <div>发音良好</div>
        </div>
        <div class="text-FF4040 text-center">
          <div>to a willing heart.</div>
          <span class="arrow bg-FF4040 my-10px inline-block"></span>
          <div>发音较差/漏读</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { formatQuestionStem } from '@/utils/question'
import Mixin from '../mixin'

export default {
  components: {},
  mixins: [Mixin],
  inject: ['_addTagClickHandler', '_removeTagClickHandler'],
  props: {
    question: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    return {}
  },
  computed: {
    stats() {
      const {
        questionId,
        stem: {
          info: { value = '', audio = '' }
        },
        answer,
        answerRecord: studentAnswer = {},
        studentScore,
        questionScore
      } = this.question

      let html = `<span class="text-FF4040">${value}</span>`
      let selfAudio = ''
      let pronunciation = 0,
        fluency = 0,
        integrity = 0

      try {
        const { anSqs } = studentAnswer
        const { anStudentUrl = '', yzsRes = '' } = anSqs[0].ans[0]
        const { lines } = JSON.parse(yzsRes)
        const {
          pronunciation: _pronunciation,
          fluency: _fluency,
          integrity: _integrity,
          words
        } = lines[0]

        pronunciation = parseInt(_pronunciation)
        fluency = parseInt(_fluency)
        integrity = parseInt(_integrity)
        selfAudio = anStudentUrl
        html = `<span>${value
          .replace(/<[^>]+>/g, '')
          .replace('.', '')
          .split(' ')
          .map((word) => {
            const yzsWordItem = words.find((w) => w.text.toLowerCase() === word.toLowerCase())
            if (yzsWordItem) {
              const { score } = yzsWordItem
              if (score < 4) {
                return `<span class="text-FF4040">${word}</span>`
              } else if (score >= 4 && score < 8) {
                return `<span class="text-F8AC23">${word}</span>`
              } else {
                return `<span class="text-30C9A1">${word}</span>`
              }
            } else {
              return `<span class="text-FF4040">${word}</span>`
            }
          })
          .join(' ')}<span>`
      } catch (error) {}

      return {
        questionId,
        stem: formatQuestionStem({
          html,
          og: null,
          sqs: [],
          type: '英语听说-短文朗读'
        }),
        pronunciation,
        fluency,
        integrity,
        stemAudio: audio,
        selfAudio,
        answer,
        studentAnswer,
        studentScore: studentScore ? studentScore : 0,
        questionScore: questionScore ? questionScore : 0
      }
    }
  },
  mounted() {
    this._addTagClickHandler('span', this.handleSpanClick)
    this._addTagClickHandler('img', this.handleImgClick)
    this._addTagClickHandler('div', this.handleDivClick)
  },
  beforeDestroy() {
    this._removeTagClickHandler('span', this.handleSpanClick)
    this._removeTagClickHandler('img', this.handleImgClick)
    this._removeTagClickHandler('div', this.handleDivClick)
  },
  methods: {
    handleSpanClick(node) {
      const parentNode = node.parentElement.children[0]

      if (parentNode && parentNode.tagName === 'IMG') {
        const { currentSrc = '' } = parentNode
        if (currentSrc.indexOf('speaker.png') != -1 || currentSrc.indexOf('my-records.png') != -1) {
          const { audioSrc, questionId } = parentNode.dataset

          if (!audioSrc || audioSrc === 'undefined') {
            currentSrc.indexOf('my-records.png') != -1 && this.$message.error('未作答')
            return
          }

          if (questionId === this.question.questionId) {
            this.playAudio(parentNode, audioSrc)

            const components = this.$parent.$parent.$refs
            for (let key in components) {
              if (Array.isArray(components[key]) && components[key].length > 0) {
                const component = components[key][0]
                const {
                  question: { questionId: _questionId }
                } = component
                if (questionId != _questionId) {
                  component.audioPlayer.pause()
                }
              }
            }
          }
        }
      }
    },
    handleImgClick(node) {
      const { currentSrc = '' } = node
      if (currentSrc.indexOf('speaker.png') != -1 || currentSrc.indexOf('my-records.png') != -1) {
        const { audioSrc, questionId } = node.dataset

        if (!audioSrc || audioSrc === 'undefined') {
          currentSrc.indexOf('my-records.png') != -1 && this.$message.error('未作答')
          return
        }

        if (questionId === this.question.questionId) {
          this.playAudio(node, audioSrc)

          const components = this.$parent.$parent.$refs
          for (let key in components) {
            if (Array.isArray(components[key]) && components[key].length > 0) {
              const component = components[key][0]
              const {
                question: { questionId: _questionId }
              } = component
              if (questionId != _questionId) {
                component.audioPlayer.pause()
              }
            }
          }
        }
      }
    },
    handleDivClick(node) {
      if (node.className.indexOf('play-btn') != -1) {
        const imgNode = node.children[0]
        const { audioSrc, questionId } = imgNode.dataset

        if (!audioSrc || audioSrc === 'undefined') {
          audioSrc.indexOf('my-records.png') != -1 && this.$message.error('未作答')
          return
        }

        if (questionId === this.question.questionId) {
          this.playAudio(imgNode, audioSrc)

          const components = this.$parent.$parent.$refs
          for (let key in components) {
            if (Array.isArray(components[key]) && components[key].length > 0) {
              const component = components[key][0]
              const {
                question: { questionId: _questionId }
              } = component
              if (questionId != _questionId) {
                component.audioPlayer.pause()
              }
            }
          }
        }
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.read-wrap {
  .overview {
    font-size: 20px;
  }

  .score {
    width: 512px;
    height: 42px;
    font-size: 16px;
    font-weight: 400;
    background-color: #edf9ff;
    margin: 0 auto;
  }

  .play {
    width: 350px;
    margin: 20px auto;

    .item {
      width: 102px;
      height: 32px;
      border-radius: 25px 25px 25px 25px;
      border: 1px solid #51c3ff;
      font-size: 16px;
      font-weight: 400;
      color: #51c3ff;

      img {
        width: 24px;
        height: 24px;
      }

      .playing {
        @keyframes play {
          0% {
            opacity: 0.5;
          }

          25% {
            opacity: 0.25;
          }

          50% {
            opacity: 0.5;
          }

          75% {
            opacity: 0.75;
          }

          100% {
            opacity: 1;
          }
        }

        animation: play 1s ease-in-out infinite backwards;
      }
    }
  }

  .rules {
    .arrow {
      width: 1px;
      height: 24px;
    }
  }
}
</style>
